import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Test18 {
    /**
     * 目的:构建一个线程池
     * 组成部分:工作线程,任务,工作线程池
     */
    static class Work extends Thread{
        private BlockingQueue<Runnable> queue = null;
        public Work(BlockingQueue<Runnable> queue){
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true){
                try {
                    Runnable tmp = queue.take();
                    tmp.run();
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    static class WorkPool{
        private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
        private List<Work> list = new ArrayList<>();
        private static final int MAX_WORK_COUNT = 10;
        public void add(Runnable runnable) throws InterruptedException {
            if (list.size() < MAX_WORK_COUNT){
                Work work = new Work(queue);
                list.add(work);
                work.start();
            }
            queue.put(runnable);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WorkPool workPool = new WorkPool();
        for (int i = 0; i < 1000; i++) {
            int tmp = i;
            workPool.add(new Runnable() {
                @Override
                public void run() {
                    System.out.println(tmp);
                }
            });
        }
    }
}
